﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YourStore.ViewModels;
using YourStore.Models;

namespace YourStore.Controllers
{
    public class StoreController : Controller
    {
        YourStoreEntities storeDB = new YourStoreEntities();

        //
        // GET: /Store/

        public ActionResult Index()
        {
            
            var categories = from cat in storeDB.Categories
                         select cat.Name;

            // Set up our ViewModelCategory
            var viewModel = new StoreIndexViewModel()
            {
                Categorys= categories.ToList(),
                NumberOfCategorys= categories.Count()
            };

            // Return the view
            return View(viewModel);
        }
        public ActionResult NewProduct()
        {
            var newproduct = GetNewProduct(6);
            return View(newproduct);
        }
        public ActionResult SearchProduct(FormCollection  fc)
        {
            string search = fc["txtSearch"];
            
            var sr = storeDB.Products.Where(p => p.Name.StartsWith(search)).ToList();
            return View(sr);
        }

        public ActionResult Browse(string category)
        {
            
            //var categoryModel = storeDB.Categories.Include("Product")
            //    .Single(c => c.Name == category);

            var categoryModel = storeDB.Categories.Single(c => c.Name == category);
            var viewModel = new StoreBrowseViewModel()
            {
                Category = categoryModel,
                Products = categoryModel.Products.ToList()
            };

            return View(viewModel);
        }

        //
        // GET: /Store/Details/5

        public ActionResult Details(int id)
        {
            var product = storeDB.Products.Single(a => a.ProductId == id);

            return View(product);
        }

        //
        
        [ChildActionOnly]
        public ActionResult Menu()
        {
            var category = storeDB.Categories.ToList();

            return View(category);
        }
        private List<Product> GetNewProduct(int count)
        {
            // Group the order details by Product and return
            // the Products with the highest count


            return storeDB.Products
                .OrderByDescending(a => a.CreatedOn)
                .Take(count)
                .ToList();

        }
    }
}
